﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.IO;
using ePlanet.Entities;
using ePlanet.SingleWell.Models;
using ePlanet.SingleWell.DataAccess;
using Web.SystemConfig.WorkFlow;
using Web.SystemConfig.SysCache;


namespace Web.Views.DataManage.PLuploads
{
    /// <summary>
    /// TemplateFileHandler 的摘要说明
    /// </summary>
    public class TemplateFileHandler : IHttpHandler
    {

        public void ProcessRequestWeb(HttpContext context)
        {
            context.Response.ContentType = "text/plain";
            string returnVal = string.Empty;
            try
            {
                string templateFileName = context.Request.QueryString["templateFileName"];
                string timeStamp = context.Request.QueryString["timeStamp"];
                string fileType = context.Request.QueryString["fileType"];
                string[] temp = templateFileName.Split('.');
                string fileNameWithoutExtension = temp[temp.Length - 2];
                string extension = temp[temp.Length - 1];
                templateFileName = fileNameWithoutExtension + '_' + timeStamp + '.' + extension;
                string tempTemplateFilePath = System.IO.Path.Combine(context.Request.PhysicalApplicationPath + "\\Views\\DataManage\\PLuploads\\tempDatas", templateFileName);
                using (FileStream fileStream = new FileStream(tempTemplateFilePath, FileMode.Create))
                {
                    byte[] tempData = new byte[context.Request.InputStream.Length];
                    context.Request.InputStream.Read(tempData, 0, tempData.Length);
                    fileStream.Write(tempData, 0, tempData.Length);
                    fileStream.Flush();
                    fileStream.Close();
                }
                if(fileType == "1")
                {
                    SingleWellDataProcess singleWellDataProcess = new SingleWellDataProcess();
                    returnVal = singleWellDataProcess.Process(tempTemplateFilePath, templateFileName);
                    context.Response.Write(returnVal);
                    context.Response.End();
                }
                else if (fileType == "2")
                { 
                    
                }
            }
            catch(Exception ex) 
            {
                throw ex;
            }
        }

        public void ProcessRequest2(HttpContext context)
        {
            context.Response.ContentType = "text/plain";
            string returnVal = string.Empty;
            try
            {
                string fileType = context.Request.QueryString["fileType"];
                HttpPostedFile file = context.Request.Files[0];
                string fileName = file.FileName;
                string fileNameWithoutExtension = Path.GetFileNameWithoutExtension(fileName);
                string fileExtension = Path.GetExtension(fileName);
                Guid guid = Guid.NewGuid();
                string tempFileName = fileNameWithoutExtension + "_" + string.Concat(guid) + fileExtension;
                string tempFilePath = context.Request.MapPath("tempDatas") + "\\" + tempFileName;
                file.SaveAs(tempFilePath);
                if (fileType == "1")
                {
                    SingleWellDataProcess singleWellDataProcess = new SingleWellDataProcess();
                    returnVal = singleWellDataProcess.Process(tempFilePath, tempFileName);
                    context.Response.Write(returnVal);
                    context.Response.End();
                }
                else if (fileType == "2")
                {

                }
            }
            catch (Exception ex)
            {
                context.Response.Write("Server Error\r\n" + ex.Message + "\r\n");
                context.Response.End();
            }
        }

        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/plain";
            string returnValue = string.Empty;
            try
            {
                string userId = context.Request.QueryString["UserId"];
                string catalogId = context.Request.QueryString["CatalogId"];
                string type = context.Request.QueryString["Type"];
                if (string.IsNullOrEmpty(userId) || string.IsNullOrEmpty(catalogId)||string.IsNullOrEmpty(type))
                {
                    throw new Exception("用户名或编目或分类为空！");
                }
                string requestData = context.Request.Form["data"].ToString();

                TemplateProcess templateProcess = new TemplateProcess();
                switch (type)
                { 
                    case "SingleWell":
                        templateProcess.SingleWellProcess(requestData,catalogId,userId);
                        break;
                    case "Archive":
                        templateProcess.ArchiveProcess(requestData, catalogId, userId);
                        break;
                    default:
                        throw new Exception("Type Error!");
                }

                context.Response.Write("Success");
            }
            catch (Exception ex)
            {
                context.Response.Write(ex.Message);
            }
        }

        private void FlowStart(Guid recordID, Guid currentUserID)
        {
            WorkFlowModel oWorkFlowModel = new WorkFlowModel();
            WorkFlow oWorkFlow = new WorkFlow();
            oWorkFlowModel.CommentMessage = string.Empty;//获取评论，在上报时候，基本是没有评论的。
            oWorkFlowModel.TableID = (int)ArchiveTableEnum.SingleWell;//获取表ID
            oWorkFlowModel.FromUserID = currentUserID;//获取当前用户ID
            oWorkFlowModel.RecordID = recordID;
            oWorkFlowModel.FromStatusID = new WorkFlowManager().GetOriginalStastuIDByTableID(ArchiveTableEnum.SingleWell);
            WorkFlowMessageStatusRuleListCache ruleCache = new ArchiveCacheFacade().GetStatusRuleCache();
            List<WorkFlowMessageStatusRule> listRule = ruleCache.GetRuleByStatusID(oWorkFlowModel.FromStatusID);
            WorkFlowMessageStatusRule rule = listRule[0];//取第一个驱动
            oWorkFlowModel.OperateID = rule.OperateID;//取驱动的ID
            oWorkFlow.FlowStart(oWorkFlowModel);//启动流程
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }



    
}